package com.hl.ui;

import java.io.IOException;
import java.lang.reflect.Type;
import java.util.Vector;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.annotation.SuppressLint;
import android.content.res.AssetFileDescriptor;
import android.graphics.Bitmap;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.media.MediaPlayer.OnCompletionListener;
import android.os.Bundle;
import android.os.Handler;
import android.os.Vibrator;
import android.view.SurfaceHolder;
import android.view.SurfaceHolder.Callback;
import android.view.SurfaceView;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.google.gson.reflect.TypeToken;
import com.google.zxing.BarcodeFormat;
import com.google.zxing.Result;
import com.hl.R;
import com.hl.app.XiaoMiApplication;
import com.hl.bean.ContactsBean;
import com.hl.qrcode.camera.CameraManager;
import com.hl.qrcode.decoding.CaptureActivityHandler;
import com.hl.qrcode.decoding.InactivityTimer;
import com.hl.qrcode.view.ViewfinderView;
import com.hl.util.LogUtils;
import com.hl.util.KL.SocketClients.Acknowledge;
import com.hl.util.KL.SocketClients.SocketClient;
import com.hl.util.KL.XmClients.IRequestCallback;
import com.hl.util.KL.XmClients.RequestMethod;
import com.hl.util.KL.XmClients.SendResult;
import com.hl.util.KL.XmClients.XmClient;
import com.hl.util.loaderConfig.AnimateFirstDisplayListener;
import com.hl.util.loaderConfig.ImageLoaderConfig;
import com.hl.util.loaderConfig.XMImageSize;
import com.hl.widget.LoadDataDialog;
import com.hl.widget.PopDialog;
import com.nostra13.universalimageloader.core.ImageLoader;

/**
 * @title 扫描界面
 * @description 扫描好友的二维码 ，整套二维码操作都是基于著名开源项目 ZXingDemo
 * @createDate 2014-01-23
 * @author 田进勇
 * 
 */
public class CaptureActivity extends NetWorkActivity implements Callback,
		IRequestCallback {
	protected static final String TAG = CaptureActivity.class.getSimpleName();
	/**
	 * IM服务器连接对象
	 */
	private SocketClient imClient;
	/**
	 * 处理消息的Handler对象
	 */
	private CaptureActivityHandler handler;
	/**
	 * 自定义的一个视图组件
	 */
	private ViewfinderView viewfinderView;
	/**
	 * 图片加载对象
	 */
	private ImageLoader imageLoader = ImageLoader.getInstance();
	private boolean hasSurface;
	private Vector<BarcodeFormat> decodeFormats;
	private String characterSet;
	private InactivityTimer inactivityTimer;
	private MediaPlayer mediaPlayer;
	private boolean playBeep;
	private static final float BEEP_VOLUME = 0.10f;
	private boolean vibrate;

	private TextView mTitle;
	private ImageView mGoHome;

	/** Called when the activity is first created. */
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		setContentView(R.layout.qr_code_scan);

		CameraManager.init(getApplication());
		initControl();

		hasSurface = false;
		inactivityTimer = new InactivityTimer(this);
	}

	private void initControl() {
		viewfinderView = (ViewfinderView) findViewById(R.id.viewfinder_view);
		mTitle = (TextView) findViewById(R.id.details_textview_title);
		mTitle.setText(R.string.scan_title);
		mGoHome = (ImageView) findViewById(R.id.details_imageview_gohome);
		mGoHome.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				finish();
			}
		});
	}

	@SuppressWarnings("deprecation")
	@Override
	protected void onResume() {
		super.onResume();
		SurfaceView surfaceView = (SurfaceView) findViewById(R.id.preview_view);
		SurfaceHolder surfaceHolder = surfaceView.getHolder();
		if (hasSurface) {
			initCamera(surfaceHolder);
		} else {
			surfaceHolder.addCallback(this);
			surfaceHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
		}
		decodeFormats = null;
		characterSet = null;

		playBeep = true;
		AudioManager audioService = (AudioManager) getSystemService(AUDIO_SERVICE);
		if (audioService.getRingerMode() != AudioManager.RINGER_MODE_NORMAL) {
			playBeep = false;
		}
		initBeepSound();
		vibrate = true;
	}

	@Override
	protected void onPause() {
		super.onPause();
		if (handler != null) {
			handler.quitSynchronously();
			handler = null;
		}
		CameraManager.get().closeDriver();
	}

	@Override
	public void onDestroy() {
		inactivityTimer.shutdown();
		super.onDestroy();
	}

	/**
	 * @param result
	 * @param barcode
	 */
	@SuppressWarnings("deprecation")
	public void handleDecode(final Result result, Bitmap barcode) {
		inactivityTimer.onActivity();
		playBeepSoundAndVibrate();

		// AlertDialog.Builder dialog = new AlertDialog.Builder(this);
		// if (barcode == null) {
		// dialog.setIcon(null);
		// } else {
		// Drawable drawable = new BitmapDrawable(barcode);
		// dialog.setIcon(drawable);
		// }
		// dialog.setTitle("扫描结果");
		// dialog.setMessage(result.getText());
		// dialog.setNegativeButton("确定", new DialogInterface.OnClickListener()
		// {
		// @Override
		// public void onClick(DialogInterface dialog, int which) {
		// // 用默认浏览器打开扫描得到的地址
		// Intent intent = new Intent();
		// intent.setAction("android.intent.action.VIEW");
		// Uri content_url = Uri.parse(result.getText());
		// intent.setData(content_url);
		// startActivity(intent);
		// finish();
		// }
		// });
		// dialog.setPositiveButton("取消", new DialogInterface.OnClickListener()
		// {
		// @Override
		// public void onClick(DialogInterface dialog, int which) {
		// finish();
		// }
		// });
		// dialog.create().show();

		// 得到用户的序号
		String userSerial = result.getText().substring(
				result.getText().indexOf("=") + 1, result.getText().length());

		reqService(userSerial);

		// finish();
	}

	private void initCamera(SurfaceHolder surfaceHolder) {
		try {
			CameraManager.get().openDriver(surfaceHolder);
		} catch (IOException ioe) {
			return;
		} catch (RuntimeException e) {
			return;
		}
		if (handler == null) {
			handler = new CaptureActivityHandler(this, decodeFormats,
					characterSet);
		}
	}

	@Override
	public void surfaceChanged(SurfaceHolder holder, int format, int width,
			int height) {

	}

	@Override
	public void surfaceCreated(SurfaceHolder holder) {
		if (!hasSurface) {
			hasSurface = true;
			initCamera(holder);
		}

	}

	@Override
	public void surfaceDestroyed(SurfaceHolder holder) {
		hasSurface = false;
	}

	public ViewfinderView getViewfinderView() {
		return viewfinderView;
	}

	public Handler getHandler() {
		return handler;
	}

	public void drawViewfinder() {
		viewfinderView.drawViewfinder();

	}

	/**
	 * 扫描正确后的震动声音,如果感觉apk大了,可以删除
	 */
	private void initBeepSound() {
		if (playBeep && mediaPlayer == null) {
			// The volume on STREAM_SYSTEM is not adjustable, and users found it
			// too loud,
			// so we now play on the music stream.
			setVolumeControlStream(AudioManager.STREAM_MUSIC);
			mediaPlayer = new MediaPlayer();
			mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
			mediaPlayer.setOnCompletionListener(beepListener);

			AssetFileDescriptor file = getResources().openRawResourceFd(
					R.raw.beep);
			try {
				mediaPlayer.setDataSource(file.getFileDescriptor(),
						file.getStartOffset(), file.getLength());
				file.close();
				mediaPlayer.setVolume(BEEP_VOLUME, BEEP_VOLUME);
				mediaPlayer.prepare();
			} catch (IOException e) {
				mediaPlayer = null;
			}
		}
	}

	private static final long VIBRATE_DURATION = 200L;

	private void playBeepSoundAndVibrate() {
		if (playBeep && mediaPlayer != null) {
			mediaPlayer.start();
		}
		if (vibrate) {
			Vibrator vibrator = (Vibrator) getSystemService(VIBRATOR_SERVICE);
			vibrator.vibrate(VIBRATE_DURATION);
		}
	}

	/**
	 * When the beep has finished playing, rewind to queue up another one.
	 */
	private final OnCompletionListener beepListener = new OnCompletionListener() {
		public void onCompletion(MediaPlayer mediaPlayer) {
			mediaPlayer.seekTo(0);
		}
	};

	@SuppressWarnings("unchecked")
	@Override
	public void Callback(SendResult<?> result) {

		if (result.getStatus() != 1) {
			Toast.makeText(getApplicationContext(), result.getMessage(),
					Toast.LENGTH_SHORT).show();
			return;
		}
		ContactsBean returnData = (ContactsBean) result.getData();
		popUI(returnData);
	}

	/**
	 * 根据扫描出来的用户序号访问服务器
	 * 
	 * @param inputValue
	 *            扫描得到的序号
	 */
	public void reqService(String inputValue) {
		XmClient<ContactsBean> client = new XmClient<ContactsBean>(this,
				new LoadDataDialog(this));

		// 参数填充
		try {
			client.setRequestPath("/api/Users/GetUser");
			client.setMethod(RequestMethod.Get);
			// 设置为请求1页 100条数据
			client.AddParam("userSerial", inputValue);

			Type type = new TypeToken<SendResult<ContactsBean>>() {
			}.getType();
			client.Send(type, this);

		} catch (Exception e) {
			e.printStackTrace();
		}

	}

	/**
	 * 弹出扫描结果
	 * 
	 * @param contactsBean
	 *            传入的对象
	 */
	public void popUI(final ContactsBean contactsBean) {
		// 弹出Dialog
		final PopDialog dialog = new PopDialog();

		dialog.sharedPopDialog(this, R.layout.dialog_order_ok, 0.8f);

		View view = dialog.getCurrentView();

		TextView msgTv = (TextView) view.findViewById(R.id.show_noca_msg);
		msgTv.setVisibility(View.GONE);

		RelativeLayout rly = (RelativeLayout) view.findViewById(R.id.left_ly);
		rly.setVisibility(View.VISIBLE);

		TextView nicNameTv = (TextView) rly.findViewById(R.id.contact_name_tv);
		nicNameTv.setText(contactsBean.getNickName());

		ImageView friendsImg = (ImageView) rly
				.findViewById(R.id.contacts_head_img);

		ImageView sexImg = (ImageView) rly.findViewById(R.id.contacts_sex_img);

		if (!contactsBean.isSex())
			sexImg.setBackgroundResource(R.drawable.sex_women);

		/**
		 * 显示图片 参数1：图片url 参数2：显示图片的控件 参数3：显示图片的设置 参数4：监听器
		 */
		String imgUrl = XMImageSize.imgFor300x300(XiaoMiApplication
				.getInstance().host + contactsBean.getImgUrl());
		imageLoader.displayImage(imgUrl, friendsImg,
				ImageLoaderConfig.initDisplayOptions(true),
				new AnimateFirstDisplayListener());

		Button leftBtn = (Button) view.findViewById(R.id.order_cancle_btn);
		Button rightBtn = (Button) view.findViewById(R.id.order_sure_btn);

		leftBtn.setText("取消");
		rightBtn.setText("加好友");

		leftBtn.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				LogUtils.i(TAG, "Cancle Add Friends!");
				dialog.dismiss();
				CaptureActivity.this.finish();
			}
		});
		rightBtn.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				// 发送请求加好友
				LogUtils.i(TAG, "AddFriends:" + contactsBean);
				addFriends(contactsBean.getUserSerial(), dialog);
			}
		});

	}

	@SuppressLint("ShowToast")
	public void addFriends(long userSerial, final PopDialog p) {
		imClient = SocketClient.getInstance();

		JSONObject data = new JSONObject();
		try {
			// 要加为好友的用户序号
			data.put("friendSerial", userSerial);
			// 用户的昵称名字
			data.put("content", XiaoMiApplication.nickname + "请求添加你为好友");
			imClient.send("addUser", data, new Acknowledge() {
				@Override
				public void acknowledge(JSONArray arguments) {
					LogUtils.i(TAG, arguments.toString());
					try {
						JSONObject returnMsg = (JSONObject) arguments.get(0);

						int status = (Integer) returnMsg.get("status");

						Toast.makeText(getApplicationContext(),
								returnMsg.get("message") + "",
								Toast.LENGTH_SHORT).show();
						if (status == 2) {
							p.dismiss();
							CaptureActivity.this.finish();
						}

					} catch (JSONException e) {
						e.printStackTrace();
					}
				}
			});
		} catch (JSONException e) {
			e.printStackTrace();
		}
	}

}
